package com.sgcc.nfc.lock.presentation.locks

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.sgcc.nfc.lock.R
import com.sgcc.nfc.lock.databinding.FragmentLocksBinding
import com.sgcc.nfc.lock.domain.model.Lock
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class LocksFragment : Fragment() {

    private var _binding: FragmentLocksBinding? = null
    private val binding get() = _binding!!
    private val viewModel: LocksViewModel by viewModels()
    private lateinit var lockAdapter: LockAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLocksBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupRecycler()
        setupListeners()
        observeViewModel()
    }

    private fun setupRecycler() {
        lockAdapter = LockAdapter(::onLockClicked, ::onLockDelete)
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = lockAdapter
        }
    }

    private fun setupListeners() {
        // 实时搜索监听器
        binding.searchEditText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            
            override fun afterTextChanged(s: Editable?) {
                val keyword = s?.toString()?.trim().orEmpty()
                viewModel.search(keyword)
            }
        })
        
        // 保留搜索键监听器作为备用
        binding.searchEditText.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                viewModel.search(v.text?.toString().orEmpty())
                true
            } else {
                false
            }
        }
    }

    private fun observeViewModel() {
        viewModel.locks.observe(viewLifecycleOwner) { locks ->
            lockAdapter.submitList(locks)
            // 显示或隐藏空状态视图
            binding.emptyStateLayout.isVisible = locks.isEmpty()
            binding.recyclerView.isVisible = locks.isNotEmpty()
        }
        
        viewModel.isLoading.observe(viewLifecycleOwner) { loading ->
            binding.progress.isVisible = loading
        }
        
        viewModel.error.observe(viewLifecycleOwner) { error ->
            error?.let {
                Snackbar.make(binding.root, it, Snackbar.LENGTH_LONG).show()
                viewModel.clearError()
            }
        }
        
        viewModel.message.observe(viewLifecycleOwner) { messageId ->
            messageId?.let {
                Snackbar.make(binding.root, getString(it), Snackbar.LENGTH_SHORT).show()
                viewModel.clearMessage()
            }
        }
    }

    private fun onLockClicked(lock: Lock) {
        val bundle = Bundle().apply { putLong("lockId", lock.lockId) }
        findNavController().navigate(R.id.lockDetailFragment, bundle)
    }

    private fun onLockDelete(lock: Lock) {
        MaterialAlertDialogBuilder(requireContext())
            .setTitle(getString(R.string.lock_delete_confirm_title))
            .setMessage(getString(R.string.lock_delete_confirm_message, lock.lockName))
            .setNegativeButton(R.string.common_cancel, null)
            .setPositiveButton(R.string.common_delete) { _, _ ->
                viewModel.deleteLock(lock.lockId)
            }
            .show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
